﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using rmeloni.Models;
using rmeloni.Helpers;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace rmeloni.Controllers
{
    public class ProjectController : Controller
    {
        //
        // GET: /Project/
        public ActionResult Index()
        {
            AllProjects();

            return View();
        }

        // GET: /Project/AllProjects
        public void AllProjects()
        {
            try
            {
                ProjectRepository prjRepo = new ProjectRepository();
                var projetos = prjRepo.SelectAll();
                var paginatedProjetos = new PaginatedList<Projetos>(projetos, 0, projetos.Count());

                ViewData["vAllProjects"] = paginatedProjetos;
            }
            catch (System.Exception)
            {
                ModelState.AddModelError("msgreturn", "Erro!!!!.");
                ViewData["vAllProjects"] = null;
            }
        }

        public void AddProject()
        {
            Projetos newProject = new Projetos();

            newProject.Nome = "SPRING";
            newProject.Descricao = "Geo";

            //read image file
            Bitmap prjImage = new Bitmap("D:\\praia.jpg");
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, prjImage);

            // read to end
            byte[] bmpBytes = ms.GetBuffer();
            prjImage.Dispose();
            ms.Close();

            newProject.Imagem = bmpBytes;

            ProjectRepository prjRepo = new ProjectRepository();
            prjRepo.Add(newProject);

            prjRepo.Save();
        }

        //
        // GET: /Project/Details/5

        public ActionResult Details(int id)
        {

            AllProjects();

            try
            {
                ProjectRepository prjRepo = new ProjectRepository();
                var projetoid = prjRepo.SelectById(id);

                if(projetoid == null)
                    return View("Index");

                if (projetoid.Imagem != null)
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    // copy the bytes to the memory
                    MemoryStream ms = new MemoryStream(projetoid.Imagem);
                    Bitmap imagem = (Bitmap)bf.Deserialize(ms);

                    ViewData["vImagem"] = imagem;
                }
                return View(projetoid);
            }
            catch (System.Exception)
            {
                ModelState.AddModelError("msgreturn", "Erro!!!!.");
            }

            return View("Index");
        }        
    }
}
